package com.px.lovepath.datebase;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import android.os.Looper;
import android.util.Log;

import com.px.lovepath.LovePathEnv;
import com.px.lovepath.ui.home.LoveMessage;
import com.px.lovepath.utils.LLog;


public class DataProvider {
	private static final String TAG = DataProvider.class.getName();
	private static final String DB_FILE_NAME = "LovePath.db";
	private final Context mContext;
	private final ManagedDatabase mDb;
	private static DataProvider mSingleton;
	
	// ### 构造函数 ###
	protected DataProvider(Context context, LovePathEnv env, DatabaseManager dbManager) {
		mContext = context;
		
		File dbFile = new File(env.getDatabaseDirectory(), DB_FILE_NAME);
		File bkFile = new File(env.getAppDataDirectory(), DB_FILE_NAME);
		mDb = dbManager.addDatabase(new ManagedDatabaseInfo(dbFile.getAbsolutePath(), bkFile.getAbsolutePath()));
		
		assert mDb != null;
		DatabaseHelper.upgrade(mContext, mDb);
	}
	
	// ### 方法 ###
	public static void startup(Context context, LovePathEnv env, DatabaseManager dbManager) {
		assert Thread.currentThread() == Looper.getMainLooper().getThread();
		assert mSingleton == null;
		
		mSingleton = new DataProvider(context, env, dbManager);
	}
	public synchronized static DataProvider get() {
		assert mSingleton != null;
		return mSingleton;
	}
	public void importMessages(List<LoveMessage> messages) {
		assert messages != null;
		try {
			mDb.beginTransaction();
			String importMessageSql = String.format(
					"INSERT INTO %s(%s TEXT, "
					+ " %s TEXT, "
					+ " %s LONG, "
					+ " %s INTEGER"
					+ ") values (?,?,?,?);"
					, 
						LoveColumns.TABLE_MESSAGE,
						LoveColumns.MESSAGE_PATH,
						LoveColumns.MESSAGE_INFO,
						LoveColumns.MESSAGE_TIME_STAMP,
						LoveColumns.MESSAGE_TYPE
					);
			SQLiteStatement statement = mDb.compileStatement(importMessageSql); 
			
			for (LoveMessage loveMessage : messages) {
				statement.bindString(0, loveMessage.getPath().toString());
				statement.bindString(1, loveMessage.getInfo());
				statement.bindLong(2, loveMessage.getDate().getTime());
				statement.bindLong(3, LoveMessage.getType(loveMessage));
				statement.execute();
			}
			
			statement.close();
			mDb.setTransactionSuccessful();
		} catch (Exception e) {
			LLog.e(TAG, "Exception : " + e.getMessage());
		} finally {
			mDb.endTransaction();
		}
	}
	/**
	 * 
	 * @param type type定于同于ConfigKey.KEY_I_SELECT
	 * @param timeLine 取该时间前的消息
	 * @return
	 */
	public LoveMessage[] getMessages(int type, long timeLine) {
		LoveMessage[] result = null;
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT * FROM messages ");
		sb.append(" WHERE timeStamp <= ");
		sb.append(timeLine);
		if (type != 0) {
			sb.append(" and type = ").append(type);
		} 
		Cursor cursor = null;
		try {
			cursor = mDb.rawQuery(sb.toString(), null);
			if (cursor != null && cursor.moveToFirst()) {
				result = new LoveMessage[cursor.getCount()];
				do {
//					result[cursor.getPosition()] = 
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			LLog.e(TAG, "Exception : " + e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			if (result == null) {
				result = new LoveMessage[0];
			}
		}
		return result;
	}
}
